﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhuXingFamilys.ExportExcel.entity;
using Org.BouncyCastle.Utilities;
using Autodesk.Revit.DB;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using System.Windows;
using ZhuXingFamilys.Help;
using System.IO;
using System.Collections.ObjectModel;
using System.Windows.Documents;

namespace ZhuXingFamilys.ExportExcel.utils
{
	internal class RulesTree
	{
		private List<RulesNode> rulesNodeList = new List<RulesNode>();
		// 数据库
		private readonly string constr = "server=8.142.144.242;database=BIMDataBase;uid=sa;pwd=1qazZSE$";
		// SQL
		private StringBuilder sqlstr = new StringBuilder();
		// 当前登录用户
		private string userName = string.Empty;
		// 规则文件路径
		private string RulesDataBasePath = string.Empty;
		// 规则文件名称
		private string RulesDataBaseFileName = "RulesDataBase.xls";
		public RulesTree(string userName)
		{
			this.userName = userName;
			// 获取规则文件路径
			RulesDataBasePath = Path.Combine(Set.getaddress(), RulesDataBaseFileName);
			this.rulesNodeList = getRulesList();
		}
		/**
         * 获取清单规则
         */
		public List<RulesNode> getRulesList()
		{
			// 数据库原始数据
			List<RulesNode> rulesNodesList = null;
			try
			{
				string path = RulesDataBasePath;
				string fileName = RulesDataBaseFileName;

				using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
				{
					byte[] bytes = new byte[fileStream.Length];
					fileStream.Read(bytes, 0, bytes.Length);
					fileStream.Close();
					MemoryStream stream = new MemoryStream(bytes);
					// 读取rulesNodes
					rulesNodesList = ExcelConvert.ToEntityStreamList<RulesNode>(stream, fileName, 0, true);
					// 读取rules
					MemoryStream stream1 = new MemoryStream(bytes);
					List<Rules> rules = ExcelConvert.ToEntityStreamList<Rules>(stream1, fileName, 1, true);
                    // 处理rulesNode
                    foreach (RulesNode rulesNode in rulesNodesList)
                    {
                        if (rulesNode.Level >= 3)
                        {
                            rulesNode.rulesList = rules.Where(r => r.NodeID == rulesNode.NodeID).ToList();
                        }
                    }
				}
			}
			catch (Exception)
			{
				MessageBox.Show("数据库文件损坏,请重新安装插件","提示");
			}

			return rulesNodesList;


			//// 数据库原始数据
			//List<RulesNode> rulesNodesList = null;
			//// 查询sql
			//sqlstr.Clear();
			//sqlstr.Append("select NodeID,ParentID,Name,Level from RulesNode ");
			//sqlstr.Append("where UserName = @UserName");
			//SqlParameter[] parm1 = { new SqlParameter("UserName", userName) };
			//// 查询数据库
			//DataTable dataTableRulesNode = SqlHelper.GetDataTable(constr, CommandType.Text, sqlstr.ToString(), parm1);
			//if (dataTableRulesNode != null && dataTableRulesNode.Rows.Count != 0)
			//{
			//	// 数据库原始数据
			//	rulesNodesList = new List<RulesNode>();
			//	foreach (DataRow ddataRowRulesNode in dataTableRulesNode.Rows)
			//	{
			//		// 封装rulesNode实体类
			//		RulesNode rulesNode = new RulesNode();
			//		rulesNode.NodeID = int.Parse(ddataRowRulesNode["NodeID"].ToString());
			//		rulesNode.ParentID = int.Parse(ddataRowRulesNode["ParentID"].ToString());
			//		rulesNode.Name = ddataRowRulesNode["Name"].ToString();
			//		rulesNode.Level = int.Parse(ddataRowRulesNode["Level"].ToString());
			//		// 封装Rules实体类
			//		if (rulesNode.Level >= 2)
			//		{
			//			sqlstr.Clear();
			//			sqlstr.Append("select RuleID,NodeID,RuleDesc,Opt,OptDesc,IsSelected,Deduction,UserName from Rules ");
			//			sqlstr.Append("where NodeID = @NodeID and UserName = @UserName");
			//			SqlParameter[] parm2 = { new SqlParameter("NodeID", rulesNode.NodeID),new SqlParameter("UserName", userName) };
			//			DataTable dataTableRules = SqlHelper.GetDataTable(constr, CommandType.Text, sqlstr.ToString(), parm2);
			//			List<Rules> rulesList1 = null;
			//			if (dataTableRules != null)
			//			{
			//				rulesList1 = new List<Rules>();
			//				//List<string> OptAndDesc = new List<string>();
			//				foreach (DataRow dataRowRules in dataTableRules.Rows)
			//				{
			//					Rules rules = new Rules();
			//					rules.RuleID = int.Parse(dataRowRules["RuleID"].ToString());
			//					rules.NodeID = int.Parse(dataRowRules["NodeID"].ToString());
			//					rules.RuleDesc = dataRowRules["RuleDesc"].ToString();
			//					rules.Opt = int.Parse(dataRowRules["Opt"].ToString());
			//					rules.OptDesc = dataRowRules["OptDesc"].ToString();
			//					rules.IsSelected = int.Parse(dataRowRules["IsSelected"].ToString());
			//					rules.Deduction = dataRowRules["Deduction"].ToString();
			//					rules.UserName = dataRowRules["UserName"].ToString();
			//					rulesList1.Add(rules);
			//					//OptAndDesc.Add(rules.Opt + " " + rules.OptDesc);
			//					//rules.OptDescList = OptAndDesc.ToArray();
			//				}
			//				rulesNode.rulesList = rulesList1;
			//			}
			//		}
			//		rulesNodesList.Add(rulesNode);
			//	}
			//}
			//else
			//{
			//	MessageBoxResult r = MessageBox.Show("检测到清单规则与服务器不同，是否更新？","提示",MessageBoxButton.YesNo);
			//	if(r==MessageBoxResult.Yes)
			//	{
			//		sqlstr.Clear();
			//		sqlstr.Append("insert into RulesNode select e.NodeID,e.ParentID,e.Name,e.Level, @UserName as UserName from RulesNode e ");
			//		sqlstr.Append("where e.UserName = 'admin'");
			//		SqlParameter[] parm3 = { new SqlParameter("UserName", userName) };
			//		SqlHelper.ExecuteNonQuery(constr, CommandType.Text, sqlstr.ToString(), parm3);

			//		sqlstr.Clear();
			//		sqlstr.Append("insert into Rules select e.RuleID,e.NodeID,e.RuleDesc,e.Opt,e.OptDesc,e.IsSelected,e.Deduction,@UserName as UserName from Rules e ");
			//		sqlstr.Append("where UserName = 'admin'");
			//		SqlParameter[] parm4 = { new SqlParameter("UserName", userName) };
			//		SqlHelper.ExecuteNonQuery(constr, CommandType.Text, sqlstr.ToString(), parm4);
			//		this.rulesNodeList = getRulesList();
			//		MessageBox.Show("更新完成，请重新打开窗口","提示");
			//	}
			//}
			//return rulesNodesList;
		}

		//建立树形结构
		public List<RulesNode> builTree()
		{
			List<RulesNode> treeRulesNodes = new List<RulesNode>();
			foreach (RulesNode rulesNode in getRootNode())
			{
				//rulesNode = buildChilTree(rulesNode);
				treeRulesNodes.Add(buildChilTree(rulesNode));
			}
			return treeRulesNodes;
		}

		//递归，建立子树形结构
		public RulesNode buildChilTree(RulesNode pNode)
		{
			List<RulesNode> chilRulesNodes = new List<RulesNode>();
			foreach (RulesNode rulesNode in rulesNodeList)
			{
				if (rulesNode.ParentID == pNode.NodeID)
				{
					chilRulesNodes.Add(buildChilTree(rulesNode));
				}
			}
			pNode.Children = chilRulesNodes;
			return pNode;
		}

		//获取根节点(获取所有的父节点)
		public List<RulesNode> getRootNode()
		{
			List<RulesNode> rootRulesNodeLists = new List<RulesNode>();
			if (rulesNodeList != null)
			{
				foreach (RulesNode rulesNode in rulesNodeList)
				{
					if (rulesNode.ParentID == 0)
					{
						rootRulesNodeLists.Add(rulesNode);
					}
				}
			}
			return rootRulesNodeLists;
		}

		// 获取所有规则
        public List<Rules> getAllRules()
        {
            try
            {
                string path = RulesDataBasePath;
                string fileName = RulesDataBaseFileName;

                using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    byte[] bytes = new byte[fileStream.Length];
                    fileStream.Read(bytes, 0, bytes.Length);
                    fileStream.Close();
                    // 读取rules
                    MemoryStream stream1 = new MemoryStream(bytes);
                    return ExcelConvert.ToEntityStreamList<Rules>(stream1, fileName, 1, true);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        // 查询详细规则列表
        public List<Rules> getRules(int nodeID)
		{
			try
			{
				string path = RulesDataBasePath;
				string fileName = RulesDataBaseFileName;

				using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
				{
					byte[] bytes = new byte[fileStream.Length];
					fileStream.Read(bytes, 0, bytes.Length);
					fileStream.Close();
					// 读取rules
					MemoryStream stream1 = new MemoryStream(bytes);
					List<Rules> rulesList = ExcelConvert.ToEntityStreamList<Rules>(stream1, fileName, 1, true);
					return rulesList.Where(r => r.NodeID == nodeID).ToList();
				}
			}
			catch (Exception)
			{
				throw;
			}


			//// 查询sql
			//sqlstr.Clear();
			//sqlstr.Append("select RuleID,NodeID,RuleDesc,Opt,OptDesc,IsSelected,Deduction,UserName from Rules ");
			//sqlstr.Append("where NodeID = @NodeID and UserName = @UserName");
			//SqlParameter[] parms = { new SqlParameter("NodeID", nodeID) ,new SqlParameter("UserName",userName)};
			//// 查询数据库
			//DataTable dataTableRules = SqlHelper.GetDataTable(constr, CommandType.Text, sqlstr.ToString(), parms);
			//List<Rules> rulesList = new List<Rules>();
			//if (dataTableRules != null)
			//{
			//	foreach (DataRow dataRowRules in dataTableRules.Rows)
			//	{
			//		Rules rules = new Rules();
			//		rules.RuleID = int.Parse(dataRowRules["RuleID"].ToString());
			//		rules.NodeID = int.Parse(dataRowRules["NodeID"].ToString());
			//		rules.RuleDesc = dataRowRules["RuleDesc"].ToString();
			//		rules.Opt = int.Parse(dataRowRules["Opt"].ToString());
			//		rules.OptDesc = dataRowRules["OptDesc"].ToString();
			//		rules.IsSelected = int.Parse(dataRowRules["IsSelected"].ToString());
			//		rules.Deduction = dataRowRules["Deduction"].ToString();
			//		rules.UserName = dataRowRules["UserName"].ToString();
			//		rulesList.Add(rules);
			//	}
			//}
			//return rulesList;
		}
		// 获取相关规则
        public List<Rules> getDependenceRules(Rules rule)
        {
            try
            {
                string path = RulesDataBasePath;
                string fileName = RulesDataBaseFileName;

                using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    byte[] bytes = new byte[fileStream.Length];
                    fileStream.Read(bytes, 0, bytes.Length);
                    fileStream.Close();
                    // 读取rules
                    MemoryStream stream1 = new MemoryStream(bytes);
                    List<Rules> rulesList = ExcelConvert.ToEntityStreamList<Rules>(stream1, fileName, 1, true);
                    return rulesList.Where(r => r.NodeName == rule.Deduction && r.Deduction == rule.NodeName && r.NodeName != r.Deduction).ToList();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        // 恢复默认
        //public bool setDefault()
        //{
        //	SqlParameter[] parm3 = { new SqlParameter("UserName", userName) };
        //	sqlstr.Clear();
        //	sqlstr.Append("update Rules set IsSelected = 0 ");
        //	sqlstr.Append("where NodeID in (select NodeID from RulesNode where UserName = @UserName )");
        //	int j = SqlHelper.ExecuteNonQuery(constr, CommandType.Text, sqlstr.ToString(), parm3);

        //	sqlstr.Clear();
        //	sqlstr.Append("update Rules set IsSelected = 1 where Opt = 0 ");
        //	sqlstr.Append("and NodeID in (select NodeID from RulesNode where UserName = @UserName )");
        //	int i = SqlHelper.ExecuteNonQuery(constr, CommandType.Text, sqlstr.ToString(), parm3);
        //	if (i == 0 || j == 0)
        //	{
        //		return false;
        //	}
        //	return true;
        //}
    }
}
